package org.jeecg.modules.demo.zyExam.zyexamaddpaper.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;

import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;

import org.jeecg.modules.demo.zyExam.zyexamaddpaper.entity.PageVo;
import org.jeecg.modules.demo.zyExam.zyexamaddpaper.entity.ZyExamAddPaper;
import org.jeecg.modules.demo.zyExam.zyexamaddpaper.mapper.ZyExamAddPaperMapper;
import org.jeecg.modules.demo.zyExam.zyexamaddpaper.service.IZyExamAddPaperService;
import org.jeecg.modules.demo.zyExam.zypaperperson.service.IZyPaperPersonService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysUserService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;

/**
 * @Description: 出卷
 * @Author: jeecg-boot
 * @Date: 2024-01-07
 * @Version: V1.0
 */
@Tag(name = "出卷")
@RestController
@RequestMapping("/zyexamaddpaper/zyExamAddPaper")
@Slf4j
public class ZyExamAddPaperController extends JeecgController<ZyExamAddPaper, IZyExamAddPaperService> {
    @Autowired
    private IZyExamAddPaperService zyExamAddPaperService;
    @Autowired
    private ZyExamAddPaperMapper zyExamAddPaperMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private org.jeecg.modules.demo.zyExam.zypapermanage.service.IZyPaperManageService zyPaperManageService;

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private IZyPaperPersonService zyPaperPersonService;
    /**
     * 分页列表查询
     *
     * @param zyExamAddPaper
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "出卷-分页列表查询")
    @Operation(summary = "出卷-分页列表查询", description = "出卷-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ZyExamAddPaper>> queryPageList(ZyExamAddPaper zyExamAddPaper,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        QueryWrapper<ZyExamAddPaper> queryWrapper = QueryGenerator.initQueryWrapper(zyExamAddPaper, req.getParameterMap());
        Page<ZyExamAddPaper> page = new Page<ZyExamAddPaper>(pageNo, pageSize);
        IPage<ZyExamAddPaper> pageList = zyExamAddPaperService.page(page, queryWrapper);
        return Result.OK(pageList);
    }
    @Operation(summary = "出卷-分页列表查询", description = "出卷-分页列表查询")
    @GetMapping(value = "/getAllPaper")
    public Result<List<Map<String,String>>> getAllPaper() {
        List<Map<String,String>> paperList = zyExamAddPaperService.getAllPaper();
        return Result.OK(paperList);
    }
    @Operation(summary = "出卷-分页列表查询", description = "出卷-分页列表查询")
    @GetMapping(value = "/getAllPaper1")
    public Result<Map<String, List<String>>> getAllPaper1(){
            List<String> paperNames = zyExamAddPaperMapper.getDistinctPaperNames();
            Map<String, List<String>> result = new HashMap<>();

            for (String paperName : paperNames) {
                List<Map<String, String>> ids = zyExamAddPaperMapper.getIdsForPaperName(paperName);
                List<String> idList = ids.stream()
                        .map(map -> map.get("id"))
                        .collect(Collectors.toList());
                result.put(paperName, idList);
            }

            return Result.ok(result);
        }



    @Operation(summary = "查询卷-出卷-分页列表查询", description = "出卷-出卷-分页列表查询")
    @GetMapping(value = "/queryBySource1")
    public Result<Map<String,Object>> queryBySource1(PageVo pageVo) {
//        String siteId = String.valueOf(redisUtil.get("siteId"));
        System.out.println("pageVo = " + pageVo);
        if (pageVo.getCurrent()==0&&pageVo.getSize()==0){
            pageVo.setCurrent(1);
            pageVo.setSize(6);
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String name=loginUser.getRealname();
        LambdaQueryWrapper<ZyExamAddPaper> queryWrapper = new LambdaQueryWrapper<ZyExamAddPaper>();
        SysUser zyRealName = Db.lambdaQuery(SysUser.class)
                .eq(SysUser::getRealname, name)
                .one();
        if (zyRealName!=null){
            queryWrapper.like(StringUtils.isNotEmpty(pageVo.getPaperName()), ZyExamAddPaper::getPaperName, pageVo.getPaperName())
                    .orderByDesc(ZyExamAddPaper::getExamDate)  // 先按日期降序
                    .orderByAsc(ZyExamAddPaper::getPaperName);  // 再按试卷名称升序
        }
        else {
            queryWrapper
                    .like(StringUtils.isNotEmpty(pageVo.getPaperName()), ZyExamAddPaper::getPaperName, pageVo.getPaperName())
                    .orderByDesc(ZyExamAddPaper::getExamDate)  // 先按日期降序
                    .orderByAsc(ZyExamAddPaper::getPaperName);  // 再按试卷名称升序
        }

        Page<ZyExamAddPaper> pageInfo = new Page<>(pageVo.getCurrent(), pageVo.getSize());
        Page<ZyExamAddPaper> resultPage = zyExamAddPaperMapper.selectPage(pageInfo, queryWrapper);
        List<ZyExamAddPaper> list = zyExamAddPaperService.list(queryWrapper);
        int listTotal=list.size();
        List<ZyExamAddPaper> records = resultPage.getRecords();
        for (ZyExamAddPaper zyExamAddPaper : records) {
            String source=zyExamAddPaper.getSource();
            zyExamAddPaper.setSource(source);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("listToatl",listTotal);
        map.put("records",records);
        return Result.ok(map);
    }


    @Operation(summary = "查询卷-出卷-分页列表查询", description = "出卷-出卷-分页列表查询")
    @GetMapping(value = "/queryBySource")
    public Result<Map<String,Object>> queryBySource(PageVo pageVo) {
//        String siteId = String.valueOf(redisUtil.get("siteId"));
        System.out.println("pageVo = " + pageVo);
        if (pageVo.getCurrent()==0&&pageVo.getSize()==0){
            pageVo.setCurrent(1);
            pageVo.setSize(6);
        }
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String name=loginUser.getRealname();
        System.out.println("name = " + name);
        LambdaQueryWrapper<ZyExamAddPaper> queryWrapper = new LambdaQueryWrapper<ZyExamAddPaper>();
        SysUser zyRealName = Db.lambdaQuery(SysUser.class)
                .eq(SysUser::getRealname, name)
                .one();
        if (name.equals("管理员")){
            queryWrapper.like(StringUtils.isNotEmpty(pageVo.getPaperName()), ZyExamAddPaper::getPaperName, pageVo.getPaperName())
                    .orderByDesc(ZyExamAddPaper::getExamDate)  // 先按日期降序
                    .orderByAsc(ZyExamAddPaper::getPaperName);  // 再按试卷名称升序
        }
        else {
            queryWrapper
                    .like(StringUtils.isNotEmpty(pageVo.getPaperName()), ZyExamAddPaper::getPaperName, pageVo.getPaperName())
                    .like(zyRealName!=null,ZyExamAddPaper::getPersonName,name)
                    .orderByDesc(ZyExamAddPaper::getExamDate)  // 先按日期降序
                    .orderByAsc(ZyExamAddPaper::getPaperName);  // 再按试卷名称升序
        }

        Page<ZyExamAddPaper> pageInfo = new Page<>(pageVo.getCurrent(), pageVo.getSize());
        Page<ZyExamAddPaper> resultPage = zyExamAddPaperMapper.selectPage(pageInfo, queryWrapper);
        List<ZyExamAddPaper> list = zyExamAddPaperService.list(queryWrapper);
        int listTotal=list.size();
        List<ZyExamAddPaper> records = resultPage.getRecords();
        for (ZyExamAddPaper zyExamAddPaper : records) {
            String source=zyExamAddPaper.getSource();
            zyExamAddPaper.setSource(source);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("listToatl",listTotal);
        map.put("records",records);
        return Result.ok(map);
    }


    @Operation(summary = "查询卷-lambda测试", description = "出卷-lambda测试")
    @GetMapping(value = "/queryByLambda")
    public Result<List<ZyExamAddPaper>> queryByLambda(PageVo pageVo) {
//        String siteId = String.valueOf(redisUtil.get("siteId"));
        if (pageVo.getCurrent()==0&&pageVo.getSize()==0){
            pageVo.setCurrent(1);
            pageVo.setSize(6);
        }
        LambdaQueryWrapper<ZyExamAddPaper> queryWrapper = new LambdaQueryWrapper<ZyExamAddPaper>()
                .like(StringUtils.isNotEmpty(pageVo.getSource()), ZyExamAddPaper::getSource, pageVo.getSource());
        Page<ZyExamAddPaper> pageInfo = new Page<>(pageVo.getCurrent(), pageVo.getSize());
        Page<ZyExamAddPaper> page = zyExamAddPaperService.page(pageInfo, queryWrapper);
        List<ZyExamAddPaper> records = page.getRecords();
        String source_code= records.get(0).getSource();
        String source=zyExamAddPaperMapper.querySource(source_code);
        for (ZyExamAddPaper zyExamAddPaper : records) {
            zyExamAddPaper.setSource(source);
        }
        ZyExamAddPaper zyExamAddPaper=new ZyExamAddPaper();
        //属性复制
        BeanUtils.copyProperties(pageVo,zyExamAddPaper);

        Map<Integer, ZyExamAddPaper> zyExamAddPaperMap = zyExamAddPaperService.list(queryWrapper)
                .stream().map(zyExamAddPaper1 -> ZyExamAddPaper.builder()
                        .examCode(zyExamAddPaper1.getExamCode())
                        .paperCode(zyExamAddPaper1.getPaperCode())
                        .paperName(zyExamAddPaper1.getPaperName())
                        .build())
                .collect(Collectors.toMap(ZyExamAddPaper::getPaperCode, v -> v));


        return Result.ok(records);
    }

    /**
     * 添加
     *
     * @param zyExamAddPaper
     * @return
     */
    @AutoLog(value = "出卷-添加")
    @Operation(summary = "出卷-添加", description = "出卷-添加")
	@RequiresPermissions("zyexamaddpaper:zy_exam_add_paper:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ZyExamAddPaper zyExamAddPaper) {
//        String siteId = String.valueOf(redisUtil.get("siteId"));
//        zyExamAddPaper.setSiteId(siteId);
        if (zyExamAddPaper.getFlag().equals("1")){
            List<SysUser> sysUsersList = Db.lambdaQuery(SysUser.class)
                    .list();
          //将sysUsersList中的realName字段集合转为用逗号隔开的字符串
            StringBuilder userNames = new StringBuilder();
            for (SysUser sysUser : sysUsersList) {
                userNames.append(sysUser.getRealname()).append(",");
            }
            //去掉最后一个逗号
            userNames.deleteCharAt(userNames.length() - 1);
            zyExamAddPaper.setPersonName(String.valueOf(userNames));
        }
        zyExamAddPaperService.save(zyExamAddPaper);
        return Result.OK("添加成功！");
    }


    /**
     * 添加多个ZyExamAddPaper对象
     *
     * @param zyExamAddPapers
     * @return
     */
    @AutoLog(value = "出卷-添加多个")
    @Operation(summary = "出卷-添加多个", description = "出卷-添加多个")
    @RequiresPermissions("zyexamaddpaper:zy_exam_add_paper:add")
    @PostMapping(value = "/addBatch")
    public Result<String> addBatch(@RequestBody List<ZyExamAddPaper> zyExamAddPapers) {
        // 批量保存
        zyExamAddPaperService.saveBatch(zyExamAddPapers);
        return Result.OK("批量添加成功！");
    }



    /**
     * 编辑
     *
     * @param zyExamAddPaper
     * @return
     */
    @AutoLog(value = "出卷-编辑")
    @Operation(summary = "出卷-编辑", description = "出卷-编辑")
	@RequiresPermissions("zyexamaddpaper:zy_exam_add_paper:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ZyExamAddPaper zyExamAddPaper) {
        zyExamAddPaperService.updateById(zyExamAddPaper);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "出卷-通过id删除")
    @Operation(summary = "出卷-通过id删除", description = "出卷-通过id删除")
	@RequiresPermissions("zyexamaddpaper:zy_exam_add_paper:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {

        Result<ZyExamAddPaper> zyExamAddPaperResult = queryById(id);
        zyPaperManageService.deleteByPaperCode(zyExamAddPaperResult.getResult().getId());
        zyPaperPersonService.deleteByPaperCode(zyExamAddPaperResult.getResult().getId());
        zyExamAddPaperService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "出卷-批量删除")
    @Operation(summary = "出卷-批量删除", description = "出卷-批量删除")
	@RequiresPermissions("zyexamaddpaper:zy_exam_add_paper:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {

        ArrayList<String> list = new ArrayList<>();
        list.addAll(Arrays.asList(ids.split(",")));
        list.forEach(id -> {zyPaperManageService.deleteByPaperCode(id);
            zyPaperPersonService.deleteByPaperCode(id);
        }
        );
//        zyPaperManageService.deleteByPaperCode(ids);

        this.zyExamAddPaperService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "出卷-通过id查询")
    @Operation(summary = "出卷-通过id查询", description = "出卷-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ZyExamAddPaper> queryById(@RequestParam(name = "id", required = true) String id) {
        ZyExamAddPaper zyExamAddPaper = zyExamAddPaperService.getById(id);

        String source= zyExamAddPaper.getSource();


        zyExamAddPaper.setSource(source);
//        zyExamAddPaper.setEnthic(enthic);
        if (zyExamAddPaper == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(zyExamAddPaper);
    }

    @Operation(summary = "查询卷-通过试卷名称查询", description = "出卷-通过试卷名称查询")
    @GetMapping(value = "/queryBySubject")
    public Result<List<ZyExamAddPaper>> queryBySubject(String subject) {
        List<ZyExamAddPaper> zyExamAddPapers = zyExamAddPaperService.queryBySubject(subject);
        return Result.ok(zyExamAddPapers);
    }



    /**
     * 导出excel
     *
     * @param request
     * @param zyExamAddPaper
     */
    @RequiresPermissions("zyexamaddpaper:zy_exam_add_paper:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZyExamAddPaper zyExamAddPaper) {
        return super.exportXls(request, zyExamAddPaper, ZyExamAddPaper.class, "出卷");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("zyexamaddpaper:zy_exam_add_paper:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZyExamAddPaper.class);
    }

}
